

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 一、建造者模式知识回顾 建造者模式是指将一个复杂的对象分解为多个简单的对象，然后一步一步构建而成。优点：  封装性好，构建和表示分离 扩展性好，各个具体的建造者相互独立，利于解耦合  缺点：  产品的组成部分必须相同，限制了使用范围 当复杂的产品内部发生变化时，建造者也需同步修改，后期的维护成本大  建造者和工厂模式的区别：  建造者更注重产品零部件的组装过程，而工厂方法模式更注重零">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式 笔记8 _ 建造者模式 在源码中的应用 StringBuilder 的 append _ MyBatis 的 SqlSessionFactoryBuilder 和 ConfigBuilder">
<meta property="og:url" content="http://example.com/2022/07/26/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B08%20_%20%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F%20%E5%9C%A8%E6%BA%90%E7%A0%81%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8%20StringBuilder%20%E7%9A%84%20append%20_%20MyBatis%20%E7%9A%84%20SqlSessionFactoryBuilder%20%E5%92%8C%20ConfigBuilder/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 一、建造者模式知识回顾 建造者模式是指将一个复杂的对象分解为多个简单的对象，然后一步一步构建而成。优点：  封装性好，构建和表示分离 扩展性好，各个具体的建造者相互独立，利于解耦合  缺点：  产品的组成部分必须相同，限制了使用范围 当复杂的产品内部发生变化时，建造者也需同步修改，后期的维护成本大  建造者和工厂模式的区别：  建造者更注重产品零部件的组装过程，而工厂方法模式更注重零">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/4ef987e6ec004228ad6b4316fa44f493.gif#pic_center">
<meta property="article:published_time" content="2022-07-26T05:50:21.000Z">
<meta property="article:modified_time" content="2022-08-22T15:41:08.554Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/4ef987e6ec004228ad6b4316fa44f493.gif#pic_center">
  
  
  
  <title>设计模式 笔记8 _ 建造者模式 在源码中的应用 StringBuilder 的 append _ MyBatis 的 SqlSessionFactoryBuilder 和 ConfigBuilder - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="设计模式 笔记8 _ 建造者模式 在源码中的应用 StringBuilder 的 append _ MyBatis 的 SqlSessionFactoryBuilder 和 ConfigBuilder"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-07-26 13:50" pubdate>
          2022年7月26日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          5.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          47 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">设计模式 笔记8 _ 建造者模式 在源码中的应用 StringBuilder 的 append _ MyBatis 的 SqlSessionFactoryBuilder 和 ConfigBuilder</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<h1 id="一、建造者模式知识回顾"><a href="#一、建造者模式知识回顾" class="headerlink" title="一、建造者模式知识回顾"></a>一、建造者模式知识回顾</h1><hr>
<p>建造者模式是指将一个复杂的对象分解为多个简单的对象，然后一步一步构建而成。<br><strong>优点：</strong></p>
<ul>
<li>封装性好，构建和表示分离</li>
<li>扩展性好，各个具体的建造者相互独立，利于解耦合</li>
</ul>
<p><strong>缺点：</strong></p>
<ul>
<li>产品的组成部分必须相同，限制了使用范围</li>
<li>当复杂的产品内部发生变化时，建造者也需同步修改，后期的维护成本大</li>
</ul>
<p><strong>建造者和工厂模式的区别：</strong></p>
<ul>
<li>建造者更注重产品零部件的组装过程，而工厂方法模式更注重零部件的创建过程</li>
</ul>
<p>（ 建造者模式和工厂方法模式可结合使用。）</p>
<p><strong>主要组成：</strong><br>1）产品角色（Product），包含多个组成部件的复杂对象，由建造者来创建其各个零件<br>2）抽象建造者（Builder），一个包含产品各个子部件的抽象方法的接口，通常还包含返回复杂产品的方法，build()<br>3）具体建造者（Concrete Builder），实现 Builder 接口，完成复杂产品的各个部件的具体创建方法<br>4）指挥者（Driver），调用建造者对象中的部件构造与状态方法完成复杂对象的创建，简单理解就是创建对象的类。</p>
<p><strong>模板代码：</strong>( 直接使用静态内部类实现 具体建造者，其中抽象建造者不用也行）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">class</span> <span class="hljs-title class_">People</span>&#123;<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> Integer age;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setAge</span><span class="hljs-params">(Integer age)</span> &#123;<br>        <span class="hljs-built_in">this</span>.age = age;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setName</span><span class="hljs-params">(String name)</span> &#123;<br>        <span class="hljs-built_in">this</span>.name = name;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> Integer <span class="hljs-title function_">getAge</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> age;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">getName</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> name;<br>    &#125;<br>    <span class="hljs-keyword">private</span> <span class="hljs-title function_">People</span><span class="hljs-params">()</span>&#123;&#125;<br>    <span class="hljs-keyword">private</span> <span class="hljs-title function_">People</span><span class="hljs-params">(String name, Integer age)</span>&#123;<br>        <span class="hljs-built_in">this</span>.name = name;<br>        <span class="hljs-built_in">this</span>.age = age;<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Builder</span>&#123;<br>        <span class="hljs-keyword">private</span> String name;<br>        <span class="hljs-keyword">private</span> Integer age;<br>        <span class="hljs-keyword">public</span> Builder <span class="hljs-title function_">name</span><span class="hljs-params">(String name)</span> &#123;<br>            <span class="hljs-built_in">this</span>.name = name;<br>            <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;<br>        &#125;<br>        <span class="hljs-keyword">public</span> Builder <span class="hljs-title function_">age</span><span class="hljs-params">(Integer age)</span> &#123;<br>            <span class="hljs-built_in">this</span>.age = age;<br>            <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;<br>        &#125;<br>        <span class="hljs-keyword">public</span> People <span class="hljs-title function_">build</span><span class="hljs-params">()</span>&#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">People</span>(name, age);<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>使用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">People</span> <span class="hljs-variable">uni</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">People</span>.Builder()<br>                .name(<span class="hljs-string">&quot;uni&quot;</span>)<br>                .age(<span class="hljs-number">22</span>)<br>                .build();<br>        System.out.println(uni);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>适用场景：</p>
<ul>
<li>相同方法，不同执行顺序，产生不同的结果</li>
<li>多个成员属性，都可以装配到一个对象，但是产生结果不同</li>
<li>产品类复杂，或者产品类中不同的调用顺序会产生不同的作用</li>
<li>初始化一个对象特别复杂，参数多，而且很多参数都有默认的值</li>
</ul>
<h1 id="二、StringBuilder-中的建造者模式"><a href="#二、StringBuilder-中的建造者模式" class="headerlink" title="二、StringBuilder 中的建造者模式"></a>二、StringBuilder 中的建造者模式</h1><hr>
<p>JDK 的 StringBuilder 类中提供了 append() 追加方法，这是一种链式创建对象的方法，开放构造步骤，最后调用了 toString() 方法就可获得完整的对象，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">String</span> <span class="hljs-variable">s</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringBuilder</span>()<br>    .append(<span class="hljs-string">&quot;hello, &quot;</span>)<br>    .append(<span class="hljs-string">&quot;Wolrd!&quot;</span>)<br>    .toString();<br></code></pre></td></tr></table></figure>
<p>StringBuilder 部分源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">StringBuilder</span><br>    <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AbstractStringBuilder</span><br>    <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Serializable</span>, CharSequence<br>&#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> StringBuilder <span class="hljs-title function_">append</span><span class="hljs-params">(Object obj)</span> &#123;<br>        <span class="hljs-keyword">return</span> append(String.valueOf(obj));<br>    &#125;<br>    ...<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">toString</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-comment">// 创建拷贝对象, 不分享内部的字符数组</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(value, <span class="hljs-number">0</span>, count);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>
<p>StringBuilder 类内部存储字符串的结构为  <code>char[] value;</code><br>是存储在父类，即抽象类 AbstractStringBuilder 中的，在StringBuillder 无参构造中，设置了字符数组默认长度为 16，当添加的字符串长度超过这个值时，其内部会有扩容机制</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-title function_">StringBuilder</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-built_in">super</span>(<span class="hljs-number">16</span>);<br>&#125;<br><br></code></pre></td></tr></table></figure>
<p>扩容机制在抽象类 AbstractStringBuilder中的ensureCapacityInternal方法实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">ensureCapacityInternal</span><span class="hljs-params">(<span class="hljs-type">int</span> minimumCapacity)</span> &#123;<br>    <span class="hljs-comment">// overflow-conscious code</span><br>    <span class="hljs-keyword">if</span> (minimumCapacity - value.length &gt; <span class="hljs-number">0</span>) &#123;<br>        value = Arrays.copyOf(value,<br>                              newCapacity(minimumCapacity));<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>
<p>我们可通过调试代码来观察其底层的扩容机制，因为底层默认长度是16，我们试试刚好append到17个字符串长度，这样其底层会进行扩容</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">String</span> <span class="hljs-variable">s</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringBuilder</span>()<br>    .append(<span class="hljs-string">&quot;1234567890&quot;</span>)<br>    .append(<span class="hljs-string">&quot;1234567&quot;</span>)<br>    .toString();<br></code></pre></td></tr></table></figure>
<p>调试过程如下图：<br><img src="https://img-blog.csdnimg.cn/4ef987e6ec004228ad6b4316fa44f493.gif#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h1 id="三、MyBatis-中的建造者模式"><a href="#三、MyBatis-中的建造者模式" class="headerlink" title="三、MyBatis 中的建造者模式"></a>三、MyBatis 中的建造者模式</h1><hr>
<p>mybatis 的 SqlSessionFactoryBuilder 类 用到了建造者模式，而且在 Mybatis中 SqlSessionFactory是由SqlSessionFactoryBuilder产生的，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SqlSessionFactoryBuilder</span> &#123;<br>    ...<br>    <span class="hljs-keyword">public</span> SqlSessionFactory <span class="hljs-title function_">build</span><span class="hljs-params">(Configuration config)</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">DefaultSqlSessionFactory</span>(config);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>DefaultSqlSessionFactory 类的有参构造需传入 Mybatis 核心配置类 Configuration 的对象作为参数，而 Configuration 内容很多，初始化比较麻烦，因此使用了专门的建造者 XMLConfigBuilder 进行创建。<br>在 SqlSessionFactoryBuilder 类中有几个重载的 build 方法，其中最主要的实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SqlSessionFactoryBuilder</span> &#123;<br>    <br>    <span class="hljs-keyword">public</span> SqlSessionFactory <span class="hljs-title function_">build</span><span class="hljs-params">(InputStream inputStream, String environment, Properties properties)</span> &#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 创建建造者 XMLConfigBuilder的 实例</span><br>            <span class="hljs-type">XMLConfigBuilder</span> <span class="hljs-variable">parser</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLConfigBuilder</span>(inputStream, environment, properties);<br>            <span class="hljs-comment">// XMLConfigBuilder 的 parse() 创建 Configuration 实例</span><br>            <span class="hljs-keyword">return</span> build(parser.parse());<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            <span class="hljs-comment">// 捕获异常</span><br>            <span class="hljs-keyword">throw</span> ExceptionFactory.wrapException(<span class="hljs-string">&quot;Error building SqlSession.&quot;</span>, e);<br>        &#125; <span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-comment">// 重置错误</span><br>            ErrorContext.instance().reset();<br>            <span class="hljs-keyword">try</span> &#123;<br>                <span class="hljs-comment">// 释放资源</span><br>                inputStream.close();<br>            &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>                <span class="hljs-comment">// IO 错误不进行处理</span><br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>XMLConfigBuilder 负责 Configuration 各个组建的创建和装配，整个装配流程如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> org.apache.ibatis.builder.xml;<br>...<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">XMLConfigBuilder</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">BaseBuilder</span> &#123;<br>    <span class="hljs-comment">// 解析配置累</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">parseConfiguration</span><span class="hljs-params">(XNode root)</span> &#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>          <span class="hljs-comment">// issue #117 read properties first</span><br>          <span class="hljs-comment">// 1.读取XML的&lt;properties&gt;标签</span><br>          propertiesElement(root.evalNode(<span class="hljs-string">&quot;properties&quot;</span>));<br>          <span class="hljs-comment">// 2. 读取XML的&lt;settings&gt;标签</span><br>          <span class="hljs-type">Properties</span> <span class="hljs-variable">settings</span> <span class="hljs-operator">=</span> settingsAsProperties(root.evalNode(<span class="hljs-string">&quot;settings&quot;</span>));<br>          <span class="hljs-comment">// 3. 加载自定义的配置</span><br>          loadCustomVfs(settings);<br>          loadCustomLogImpl(settings);<br>          <span class="hljs-comment">// 4. 加载XML的&lt;typeAliases&gt; 标签</span><br>          typeAliasesElement(root.evalNode(<span class="hljs-string">&quot;typeAliases&quot;</span>));<br>          <span class="hljs-comment">// 5. 加载XML的 &lt;plugins&gt; 标签</span><br>          pluginElement(root.evalNode(<span class="hljs-string">&quot;plugins&quot;</span>));<br>          <span class="hljs-comment">// 6. 加载XML的&lt;objectFactory&gt; 标签</span><br>          objectFactoryElement(root.evalNode(<span class="hljs-string">&quot;objectFactory&quot;</span>));<br>          <span class="hljs-comment">// 7. 加载XML的&lt;objectWrapperFactory&gt;标签</span><br>          objectWrapperFactoryElement(root.evalNode(<span class="hljs-string">&quot;objectWrapperFactory&quot;</span>));<br>          <span class="hljs-comment">// 8. 加载XML的&lt;reflectorFactory&gt; 标签</span><br>          reflectorFactoryElement(root.evalNode(<span class="hljs-string">&quot;reflectorFactory&quot;</span>));<br>          <span class="hljs-comment">// 9. 更新设置</span><br>          settingsElement(settings);<br>          <span class="hljs-comment">// read it after objectFactory and objectWrapperFactory issue #631</span><br>          <span class="hljs-comment">// 10. 加载XML的&lt;environments&gt; 标签</span><br>          environmentsElement(root.evalNode(<span class="hljs-string">&quot;environments&quot;</span>));<br>          <span class="hljs-comment">// 11. 加载XML的 &lt;databaseIdProvider&gt; 标签</span><br>          databaseIdProviderElement(root.evalNode(<span class="hljs-string">&quot;databaseIdProvider&quot;</span>));<br>          <span class="hljs-comment">// 12. 加载XML的 &lt;typeHandlers&gt; 标签</span><br>          typeHandlerElement(root.evalNode(<span class="hljs-string">&quot;typeHandlers&quot;</span>));<br>          <span class="hljs-comment">// 13. 加载XML的 &lt;mappers&gt; 标签</span><br>          mapperElement(root.evalNode(<span class="hljs-string">&quot;mappers&quot;</span>));<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>          <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">BuilderException</span>(<span class="hljs-string">&quot;Error parsing SQL Mapper Configuration. Cause: &quot;</span> + e, e);<br>        &#125;<br>     &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>XMLConfigBuilder 类负责创建复杂对象 Configuration，可以视为具体建造者角色，而SqlSessionFactoryBuilder则是以封装式构建 SqlSessionFactory 实例，相当于简化的建造者模式。</p>
<h1 id="四、总结"><a href="#四、总结" class="headerlink" title="四、总结"></a>四、总结</h1><hr>
<p>本次学习的建造者模式分别在JDK源码的StringBuilder的 append()方法 、toString()方法 和 Mybatis源码的 SqlSessionFactoryBuilder 和 配置文件XMLConfigBuilder。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" class="category-chain-item">设计模式</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">#设计模式</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>设计模式 笔记8 _ 建造者模式 在源码中的应用 StringBuilder 的 append _ MyBatis 的 SqlSessionFactoryBuilder 和 ConfigBuilder</div>
      <div>http://example.com/2022/07/26/设计模式 笔记8 _ 建造者模式 在源码中的应用 StringBuilder 的 append _ MyBatis 的 SqlSessionFactoryBuilder 和 ConfigBuilder/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年7月26日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/07/26/ClickHouse%20%E7%AC%94%E8%AE%B01%20_%20%E7%AE%80%E4%BB%8B%E3%80%81%E7%89%B9%E7%82%B9%20_%20%E5%9F%BA%E4%BA%8ECentOS7%E7%B3%BB%E7%BB%9F%E7%9A%84%E5%AE%89%E8%A3%85%E4%B8%8E%E4%BD%BF%E7%94%A8%20_%20%E5%B8%B8%E7%94%A8%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%20_%20MergeTree%20%E8%A1%A8%E5%BC%95%E6%93%8E%20_%20SQL%E6%93%8D%E4%BD%9C/" title="ClickHouse 笔记1 _ 简介、特点 _ 基于CentOS7系统的安装与使用 _ 常用数据类型 _ MergeTree 表引擎 _ SQL操作">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">ClickHouse 笔记1 _ 简介、特点 _ 基于CentOS7系统的安装与使用 _ 常用数据类型 _ MergeTree 表引擎 _ SQL操作</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/07/25/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B07%20_%20%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F%20%E5%9C%A8%E6%BA%90%E7%A0%81%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8%20Spring%E7%AF%87/" title="设计模式 笔记7 _ 抽象工厂模式 在源码中的应用 Spring篇">
                        <span class="hidden-mobile">设计模式 笔记7 _ 抽象工厂模式 在源码中的应用 Spring篇</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
